<template>
	<el-card>
		<div class="scheduleDivClass">
			<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
				<el-form-item>
					<el-input v-model="state.queryForm.name" placeholder="调度任务名称"></el-input>
				</el-form-item>
				<el-form-item>
					<!-- @change="change" -->
					<el-select v-model="state.queryForm.groupId" placeholder="所属调度组" clearable>
						<el-option v-for="item in state.projectList" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<fast-select v-model="state.queryForm.status" dict-type="release_status" placeholder="发布状态" clearable></fast-select>
				</el-form-item>
				<el-form-item>
					<el-button @click="getDataList()" :icon="Search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button v-auth="'data-development:schedule:save'" :icon="Plus" type="primary" @click="addOrUpdateHandle()">新建</el-button>
				</el-form-item>
				<!-- <el-form-item>
					<el-button v-auth="'data-development:schedule:delete'" type="danger" @click="deleteBatchHandle()">删除</el-button>
				</el-form-item> -->
			</el-form>
			<el-table
				:height="cardDetailsTableHeight"
				v-loading="state.dataListLoading"
				:data="state.dataList"
				border
				style="width: 100%"
				@selection-change="selectionChangeHandle"
			>
				<!-- <el-table-column type="selection" header-align="center" :selectable="selectEnable" align="center" width="50"></el-table-column> -->
				<el-table-column prop="id" label="主键ID" header-align="center" align="center" width="100"></el-table-column>
				<el-table-column prop="name" label="调度任务名称" header-align="center" align="center"></el-table-column>
				<el-table-column prop="groupName" label="所属调度组" header-align="center" align="center"></el-table-column>
				<el-table-column prop="cron" label="cron表达式" header-align="center" align="center">
					<template #default="scope">
						<el-tag>{{ scope.row.cron }}</el-tag>
					</template>
				</el-table-column>
				<fast-table-column prop="status" label="发布状态" dict-type="release_status" header-align="center" align="center"></fast-table-column>
				<fast-creator-column prop="releaseUserId" label="发布人" header-align="center" align="center"></fast-creator-column>
				<el-table-column show-overflow-tooltip prop="releaseTime" label="发布时间" header-align="center" align="center"></el-table-column>
				<fast-creator-column prop="creator" label="创建人" header-align="center" align="center"></fast-creator-column>
				<el-table-column show-overflow-tooltip prop="createTime" label="创建时间" header-align="center" align="center"></el-table-column>
				<el-table-column show-overflow-tooltip prop="updateTime" label="最近更新时间" header-align="center" align="center"></el-table-column>
				<el-table-column label="操作" fixed="right" header-align="center" align="center" width="280">
					<template #default="scope">
						<el-button type="primary" link @click="getDetail(scope.row.id)">查看</el-button>
						<el-button
							:disabled="scope.row.status == 1"
							v-auth="'data-development:schedule:run'"
							type="primary"
							link
							@click="runFlowHandle(scope.row.id)"
							>执行</el-button
						>
						<el-button v-if="scope.row.status == 0" v-auth="'data-development:schedule:release'" type="primary" link @click="release(scope.row.id)"
							>发布</el-button
						>
						<el-button v-if="scope.row.status == 1" v-auth="'data-development:schedule:cancle'" type="primary" link @click="cancle(scope.row.id)"
							>撤回</el-button
						>
						<el-button
							:disabled="scope.row.status == 1"
							v-auth="'data-development:schedule:update'"
							type="primary"
							link
							@click="addOrUpdateHandle(scope.row.id)"
							>编辑</el-button
						>
						<el-button
							:disabled="scope.row.status == 1"
							v-auth="'data-development:schedule:delete'"
							type="primary"
							link
							@click="deleteBatchHandleTwo(scope.row.id)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				:current-page="state.page"
				:page-sizes="state.pageSizes"
				:page-size="state.limit"
				:total="state.total"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="sizeChangeHandle"
				@current-change="currentChangeHandle"
			>
			</el-pagination>
			<!-- 弹窗, 新建 / 修改 -->
			<div class="drawerClass" style="height: 100%" v-if="flowVisable">
				<el-drawer
					:title="state.drawerTitle"
					size="100%"
					:show-close="false"
					v-model="flowVisable"
					direction="rtl"
					:modal="false"
					:close-on-click-modal="false"
				>
					<Flow ref="flowRef" :childProp="state.queryForm.groupId" @refreshDataList="refreshData"></Flow>
					<el-button class="btnReturn" @click="btnReturnFun(1)">返回</el-button>
				</el-drawer>
			</div>

			<!-- 弹窗, 查看 -->
			<div class="drawerClass" style="height: 100%" v-if="detailVisable">
				<el-drawer
					:show-close="false"
					title="查看流程"
					size="100%"
					v-model="detailVisable"
					direction="rtl"
					:modal="false"
					:close-on-click-modal="false"
				>
					<Detail :childProp="state.queryForm.groupId" ref="detailRef"></Detail>
					<el-button class="btnReturn" @click="btnReturnFun(2)">返回</el-button>
				</el-drawer>
			</div>
			<!-- 弹窗, 执行 -->
			<!-- <div class="drawerClass" style="height: 100%" v-if="executeVisable">
				<el-drawer
					title="执行流程"
					size="100%"
					:show-close="false"
					v-model="executeVisable"
					direction="rtl"
					:modal="false"
					:close-on-click-modal="false"
				>
					<executeFlow ref="executeRef" :childProp="state.queryForm.groupId" @refreshDataList="refreshData"></executeFlow>
					<el-button class="btnReturn" @click="btnReturnFun(3)">返回</el-button>
				</el-drawer>
			</div> -->

			<div class="drawerClass" style="height: 100%" v-if="executeVisable">
				<el-drawer
					title="执行流程"
					size="100%"
					:show-close="false"
					v-model="executeVisable"
					direction="rtl"
					:modal="false"
					:close-on-click-modal="false"
				>
					<executeFlow ref="executeRef" :childProp="state.queryForm.groupId" @refreshDataList="refreshData"></executeFlow>
					<el-button class="btnReturn" @click="btnReturnFun(3)">返回</el-button>
				</el-drawer>
			</div>
		</div>
	</el-card>
</template>

<script setup lang="ts" name="Data-developmentScheduleIndex">
import { Delete, Edit, Search, Plus, CircleClose, Refresh } from '@element-plus/icons-vue'
import { useCrud } from '@/hooks'
import { reactive, ref, onMounted, watch } from 'vue'
import Flow from './flow.vue'
import Detail from './detail.vue'
import executeFlow from './executeFlow.vue'
import { IHooksOptions } from '@/hooks/interface'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { getDictLabel } from '@/utils/tool'
import { releaseApi, cancleApi } from '@/api/data-development/schedule'
import { ScheduleGroupList, estimatBoolean } from '@/api/auth-hm'
import { useRouter } from 'vue-router'

const state: IHooksOptions = reactive({
	dataListUrl: '/data-development/schedule/page',
	deleteUrl: '/data-development/schedule',
	queryForm: {
		name: '',
		groupId: '',
		status: ''
	},
	projectList: [],
	drawerTitle: ''
})
onMounted(() => {
	getCardDetailsTableHeight()
	ScheduleGroupListFun()
})

const selectEnable = (row, index) => {
	if (row.status != '1') {
		return true
	} else {
		return false
	}
}

const ScheduleGroupListFun = () => {
	ScheduleGroupList({}).then((res: any) => {
		if (res.code == 0) {
			let dataList = res.data && res.data.length > 0 ? res.data : []
			let dataObj = []
			for (let i = 0; i < dataList.length; i++) {
				let obj = {
					value: '',
					label: ''
				}
				obj.value = dataList[i].id
				obj.label = dataList[i].groupName
				dataObj.push(obj)
			}
			state.projectList = dataObj
		} else {
			ElMessage.error(res.msg)
		}
	})
}
const refreshData = () => {
	// flowVisable.value = false
	// getDataList()

	setTimeout(function () {
		location.reload()
	}, 1000)
}
const btnReturnFun = item => {
	if (item == 1) {
		flowVisable.value = false
	} else if (item == 2) {
		detailVisable.value = false
	} else {
		executeVisable.value = false
	}
}
const router = useRouter()
// const change = item => {
// 	getDataList()
// }
const cardDetailsTableHeight: any = ref()
// 动态设置表格高度
const getCardDetailsTableHeight = () => {
	let tableH = 265 //距离页面下方的高度
	let tableHeightDetil = window.innerHeight - tableH
	if (tableHeightDetil <= 100) {
		cardDetailsTableHeight.value = 100
	} else {
		cardDetailsTableHeight.value = window.innerHeight - tableH
	}
}
// 监听窗口变化动态设置表格高度
window.onresize = () => {
	getCardDetailsTableHeight()
}
/**
 * 查看详情
 */
const detailVisable = ref(false)
const executeVisable = ref(false)
const detailRef = ref()
const getDetail = id => {
	detailVisable.value = true
	initDetailRef(id)
	// flowVisable.value = true
	// initFlowRef(id, true, '1111')
}
const initDetailRef = async id => {
	if (detailRef.value) {
		await detailRef.value.init(id)
		// 查看
		await detailRef.value.runFlow(id)
		return
	}
	setTimeout(() => {
		initDetailRef(id)
	}, 500)
}

/**
 * 编辑流程
 */
const flowVisable = ref(false)
const flowRef = ref()
const executeRef = ref()
const addOrUpdateHandle = (id?: number) => {
	if (id) {
		state.drawerTitle = '编辑流程'
		// 点击编辑  调接口判断
		estimatBoolean(id).then((res: any) => {
			if (res.code == 0) {
				if (res.data == '0') {
					flowVisable.value = true
					initFlowRef(id)
				} else {
					ElMessage.error('正在执行，不允许编辑操作')
				}
			} else {
				ElMessage.error(res.msg)
			}
		})
	} else {
		state.drawerTitle = '新建流程'
		flowVisable.value = true
		initFlowRef()
	}
}
const initFlowRef = (id, ifRun, num) => {
	if (flowRef.value) {
		flowRef.value.init(id, ifRun, num)
		return
	}
	setTimeout(() => {
		initFlowRef(id, ifRun, num)
	}, 500)
}

/**
 * 执行
 */
const initExecuteRef = (id, ifRun, num) => {
	if (executeRef.value) {
		executeRef.value.init(id, ifRun, num)
		return
	}
	setTimeout(() => {
		initExecuteRef(id, ifRun, num)
	}, 500)
}

const runFlowHandle = id => {
	// 点击编辑  调接口判断
	estimatBoolean(id).then((res: any) => {
		if (res.code == 0) {
			if (res.data == '0') {
				// 最后需执行
				ElMessageBox.confirm('确定执行吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						// 编辑
						// flowVisable.value = true
						// initFlowRef(id, true, '1111')
						getDataList()
						// 跳转查看
						executeVisable.value = true
						initExecuteRef(id, true, '1111')
					})
					.catch(() => {})
			} else {
				ElMessage.error('正在执行，不允许执行操作')
			}
		} else {
			ElMessage.error(res.msg)
		}
	})
}

/**
 * 发布
 */
const release = id => {
	estimatBoolean(id).then((res: any) => {
		if (res.code == 0) {
			if (res.data == '0') {
				ElMessageBox.confirm('确定发布吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						releaseApi(id).then(res => {
							ElMessage.success('发布成功')
							getDataList()
						})
					})
					.catch(() => {})
			} else {
				ElMessage.error('正在执行，不允许发布操作')
			}
		} else {
			ElMessage.error(res.msg)
		}
	})
}
// 删除
const deleteBatchHandleTwo = id => {
	estimatBoolean(id).then((res: any) => {
		if (res.code == 0) {
			if (res.data == '0') {
				deleteBatchHandle(id)
			} else {
				ElMessage.error('正在执行，不允许删除操作')
			}
		} else {
			ElMessage.error(res.msg)
		}
	})
}
/**
 * 取消发布
 */
const cancle = id => {
	ElMessageBox.confirm('确定取消发布吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			cancleApi(id).then(res => {
				ElMessage.success('取消发布成功')
				getDataList()
			})
		})
		.catch(() => {})
}

/* const handleClose = () => {
  ElMessageBox.confirm('确定关闭吗？','提示' {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
    .then(() => {
      //done()
    })
    .catch(() => {
    })
} */

const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
watch(
	() => router.currentRoute.value.query,
	toPath => {
		if (router.currentRoute.value.query.schedulerRroupId) {
			state.queryForm.groupId = Number(router.currentRoute.value.query.schedulerRroupId)
			// getDataList()
		} else {
			state.queryForm.groupId = ''
		}
	},
	{ immediate: true, deep: true }
)
</script>

<style lang="scss">
.scheduleDivClass {
	height: calc(100vh - 165px);
	/* :deep .el-overlay {
			position: absolute;
		} */
	position: relative;
	overflow: hidden;
}
.scheduleDivClass > .drawerClass > div {
	height: 100%;
	position: absolute !important;
	overflow: hidden;
	z-index: 99;
}
.drawerClass .el-drawer__header {
	height: 5%;
	border: 0;
	overflow: hidden;
}
.drawerClass .el-drawer__body {
	height: calc(95% - 10px);
	padding: 0;
	margin-top: 10px;
}
/* 占比el-drawer__body的100% */
.drawerClass .el-drawer__body .el-card {
	height: 100%;
}
.drawerClass .el-drawer__body .el-card .el-card__body {
	height: 100%;
}
.drawerClass .btnReturn {
	position: absolute;
	top: 0px;
	right: 0;
}
</style>
